package com.service.entrance;

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.PrintStream;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

import com.service.cache.CacheManager;
import com.service.other.AbendHook;
import com.service.other.GUIPrintStream;
import com.service.other.Logger;
import com.service.other.ServerClose;
import com.service.other.ServerConfig;
import com.service.scheduler.server.SchedulerServer;
import com.service.socket.server.VehicleServer;

public class Program extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	public static Program frame =null;
	
	private boolean bStartComplete = false;
	private boolean bCloseStart = false;
	private final JTextArea textArea = new JTextArea();
	private final JButton btnStartup = new JButton("启动");
	private final JButton btnStop = new JButton("关闭");
	private final JButton btnClear = new JButton("消息清空");
	private final JLabel lblArea = new JLabel("消息：");
	private final JCheckBox chkScroll = new JCheckBox("滚动锁定");	
	private AbendHook abendHook = new AbendHook();

	public static Program instance(){
		if(frame == null){
			frame =new Program();			
		}
		return frame;
	}
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					System.out.println("startup");
					Program.instance().setVisible(true);
					CacheManager.instance();
					
					//消息重定向输出到画面
					PrintStream printStream = new PrintStream(new GUIPrintStream(System.out,Program.instance().textArea,Program.instance().chkScroll));
					System.setOut(printStream);
					System.setErr(printStream);
				} catch (Exception e) {
					Logger.err(e);
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Program() {
		setTitle("车辆服务器  server_port:"+ ServerConfig.instance().server_port);
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setBounds(100, 100, 675, 422);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		GridBagLayout gbl_contentPane = new GridBagLayout();
		gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0, 188, 0, 0, 0};
		gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0};
		gbl_contentPane.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE};
		gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		contentPane.setLayout(gbl_contentPane);
				
		//启动按钮
		GridBagConstraints gbc_btnRun = new GridBagConstraints();
		gbc_btnRun.anchor = GridBagConstraints.WEST;
		gbc_btnRun.insets = new Insets(0, 0, 5, 5);
		gbc_btnRun.gridx = 0;
		gbc_btnRun.gridy = 0;
		contentPane.add(btnStartup, gbc_btnRun);
		
		//关闭按钮
		GridBagConstraints gbc_btnStop = new GridBagConstraints();
		gbc_btnStop.anchor = GridBagConstraints.WEST;
		gbc_btnStop.insets = new Insets(0, 0, 5, 5);
		gbc_btnStop.gridx = 0;
		gbc_btnStop.gridy = 1;
		contentPane.add(btnStop, gbc_btnStop);
		
		//消息label
		GridBagConstraints gbc_lblArea = new GridBagConstraints();
		gbc_lblArea.insets = new Insets(0, 0, 5, 5);
		gbc_lblArea.gridx = 0;
		gbc_lblArea.gridy = 2;
		contentPane.add(lblArea, gbc_lblArea);
		
		GridBagConstraints gbc_btnClear = new GridBagConstraints();
		gbc_btnClear.insets = new Insets(0, 0, 5, 5);
		gbc_btnClear.gridx = 5;
		gbc_btnClear.gridy = 2;
		contentPane.add(btnClear, gbc_btnClear);
		
		GridBagConstraints gbc_chkScroll = new GridBagConstraints();
		gbc_chkScroll.insets = new Insets(0, 0, 5, 0);
		gbc_chkScroll.gridx = 6;
		gbc_chkScroll.gridy = 2;
		contentPane.add(chkScroll, gbc_chkScroll);
		
		//消息textArea
		JScrollPane scrollPane = new JScrollPane();
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.gridwidth = 7;
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridx = 0;
		gbc_scrollPane.gridy = 3;
		contentPane.add(scrollPane, gbc_scrollPane);				
		scrollPane.setViewportView(textArea);
		
		//启动按钮事件追加
		btnStartup.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {				
				btnStartup.setEnabled(false);				
				startup();
			}
		});
		
		//关闭按钮事件追加		
		btnStop.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				close();
			}
		});
		
		//清空按钮事件追加
		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				clear();
			}
		});		
		
		// 画面右上角关闭处理
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				close();
			}
		});
	}

	/**
	 * 服务器启动处理
	 */
	private void startup() {
		new Thread(new Runnable(){
			@Override
			public void run() {
				Runtime.getRuntime().addShutdownHook(abendHook);
				try {
					VehicleServer.instance().run();
					SchedulerServer.instance().run();
				} catch (Exception e) {
					Logger.err(e);
				}finally{
					bStartComplete = true;
				}
			}			
		}).start();

	}
	
	/**
	 * 消息清空处理
	 */	
	private void clear() {
		textArea.setText("");
	}	
	
	
	/**
	 * 画面关闭处理
	 */	
	private void close() {
		//画面初始化场合
		if (btnStartup.isEnabled()){
			//服务器未启动
			JOptionPane.showMessageDialog(null, "画面关闭");
			System.exit(0);
			return;
		}else{
			//服务器正在启动的场合
			if (!bStartComplete){
				JOptionPane.showMessageDialog(null, "请等待...服务器正在启动");
				return;  
			}
		}

		//服务器正在关闭的场合
		if (bCloseStart){
			//关闭处理ing
			JOptionPane.showMessageDialog(null, "请等待...服务器正在关闭");
			return;  
		}

    	//服务器运行，触发关闭事件
		new Thread(new Runnable(){
			@Override
			public void run() {
				int choose = JOptionPane.showConfirmDialog(null, "服务器确认关闭？","message提示", JOptionPane.OK_OPTION);		
			    if (choose == JOptionPane.YES_OPTION) {			    	
					try {
				    	bCloseStart = true;
						ServerClose.close();
					} catch (Exception e) {
					}finally{
						//程序退出
						Runtime.getRuntime().removeShutdownHook(abendHook);
						System.exit(0);
					}
					return;
			    } else if (choose == JOptionPane.NO_OPTION) {
			    	return;    
			    }
			}			
		}).start();
	}
}
